package com.shell.governor.user.rx;

import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.governor.user.UserEvent;
import com.shell.governor.user.dao.PubUserDao;
import com.shell.governor.user.dao.PubUserExtraDao;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.po.PubUserExtra;
import com.shell.governor.user.po.PubUserOpt;
import com.shell.governor.user.service.PubUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UpdateUserStateSubscriber extends OnErrorNotImplementedSubscriber<UserEvent> {
	@Autowired
	PubUserDao pubUserDao;
	@Autowired
	PubUserExtraDao pubUserExtraDao;
	@Autowired
	PubUserService pubUserService;

	public void onApplicationEvent(UserEvent event) {
		PubUserOpt userOpt = event.getUserOpt();
		PubUser user = (PubUser) this.pubUserDao.selectByPrimaryKey(userOpt.getUserId());
		PubUserExtra userExtra = new PubUserExtra();
		userExtra.setUserId(userOpt.getUserId());
		userExtra.setEntId(userOpt.getEntId());
		userExtra = (PubUserExtra) this.pubUserExtraDao.selectOne(userExtra);
		userExtra.setUserState(userOpt.getCurState());

		event.setUser(user);
		event.setUserExtra(userExtra);
		if (!this.pubUserService.hasDefaultUser(user.getUserId())) {
			this.pubUserService.cleanDefaultUser(user.getUserId());
			userExtra.setIsDefault("1");
		} else {
			userExtra.setIsDefault("0");
		}
		this.pubUserExtraDao.updateByPrimaryKey(userExtra);
	}
}